package com.tian.framework.security.util;

import com.tian.framework.security.domian.SecurityRole;
import com.tian.framework.security.domian.SecurityUser;
import com.tian.framework.security.server.ISecurityService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private ISecurityService iSecurityService;
    private static final Logger log = LogManager.getLogger(UserDetailsServiceImpl.class);

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //log.info("用户的用户名密码: {}", new BCryptPasswordEncoder().encode("1"));
        // 封装用户信息，并返回。参数分别是：用户名，密码，用户权限
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        SecurityUser sysUser = iSecurityService.selectSecurityUserByName(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //添加权限
        List<SecurityRole> roles = sysUser.getRoles();
        //添加角色信息
        for (SecurityRole role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleKey().toUpperCase()));
        }
        //添加普通权限
        List<String> perms = iSecurityService.selectUserPermissionByUserId(sysUser.getUserId());
        for (String perm : perms) {
            authorities.add(new SimpleGrantedAuthority(perm));
        }
        User user = new User(sysUser.getUserName(), sysUser.getPassword(), sysUser.getEnabled(),
                sysUser.getAccountNonExpired(), sysUser.getCredentialsNonExpired(), sysUser.getAccountNonLocked(), authorities);
        return user;
    }
}
